package com.zichen.pr.system.controller;

import com.zichen.pr.common.core.controller.BaseController;
import com.zichen.pr.common.core.domain.entity.SysDictData;
import com.zichen.pr.common.core.domain.result.Result;
import com.zichen.pr.common.core.page.TableDataInfo;
import com.zichen.pr.system.service.SysDictDataService;
import com.zichen.pr.system.service.SysDictTypeService;
import com.zichen.pr.util.SecurityUtils;
import com.zichen.pr.util.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: pr
 * @description: 数据信息
 * @author: rzhang
 * @create: 2021-04-02 07:41
 */
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController {

    @Resource(name = "sysDictTypeService")
    private SysDictTypeService sysDictTypeService;

    @Resource(name = "sysDictDataService")
    private SysDictDataService sysDictDataService;

    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDictData dictData) {
        startPage();
        List<SysDictData> list = sysDictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

    /**
     * 查询字典数据详细
     */
    @PreAuthorize("@ss.hasPermi('system:dict:query')")
    @GetMapping(value = "/{dictCode}")
    public Result getInfo(@PathVariable Long dictCode) {
        return Result.success(sysDictDataService.getById(dictCode));
    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public Result dictType(@PathVariable String dictType) {
        List<SysDictData> data = sysDictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data)) {
            data = new ArrayList<SysDictData>();
        }
        return Result.success(data);
    }

    /**
     * 新增字典数据
     */
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @PostMapping
    public Result add(@Validated @RequestBody SysDictData dict) {
        dict.setCreateBy(SecurityUtils.getUsername());
        return toAjax(sysDictDataService.save(dict));
    }

    /**
     * 修改保存字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @PutMapping
    public Result edit(@Validated @RequestBody SysDictData dict) {
        dict.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysDictDataService.updateById(dict));
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @DeleteMapping("/{dictCodes}")
    public Result remove(@PathVariable Long[] dictCodes) {
        return toAjax(sysDictDataService.removeByIds(Arrays.asList(dictCodes)));
    }
}
